<?php
require './function.php';

/**
 * @Author: Wherein
 * @Date: 2021-03-30 15:58
 * @Descripttion: 代理模式
 * @example 通过代理实现MySQL的读写分离，如果是读操作，就连接127.0.0.1的数据库，写操作就读取127.0.0.2的数据库
 */

class Proxy{
    public $reader;
    public $writer;

    public function __construct()
    {
        $this->reader = new PDO('mysql:host=127.0.0.1;port=3306;dbname=data_analysis', 'root', 'root');
        $this->writer = new PDO('mysql:host=127.0.0.2;port=3306;dbname=data_analysis', 'root', 'root');
    }

    public function query($sql){
        if (substr($sql, 0, 6) == 'select') {
            // 读操作
            dd('读操作');
            return $this->reader->query($sql);
        } else {
            dd('写操作');
            return $this->writer->query($sql);
        }
    }
}

$proxy = new Proxy();
$res1 = $proxy->query('select * from ims_account');

$res2 = $proxy->query('insert into `ims_basic_reply` set rid=1,content="1212"');

dd($res1, $res2);
